// 性能优化工具类
export default {
  // 图片懒加载
  lazyLoad: {
    // 创建懒加载观察器
    createObserver(callback) {
      // #ifdef H5
      if (typeof IntersectionObserver !== 'undefined') {
        return new IntersectionObserver(callback, {
          rootMargin: '50px'
        })
      }
      // #endif
      return null
    },
    
    // 观察元素
    observe(observer, element) {
      if (observer && element) {
        observer.observe(element)
      }
    },
    
    // 取消观察
    unobserve(observer, element) {
      if (observer && element) {
        observer.unobserve(element)
      }
    }
  },
  
  // 防抖函数
  debounce(func, wait, immediate = false) {
    let timeout
    return function executedFunction(...args) {
      const later = () => {
        timeout = null
        if (!immediate) func.apply(this, args)
      }
      const callNow = immediate && !timeout
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) func.apply(this, args)
    }
  },
  
  // 节流函数
  throttle(func, limit) {
    let inThrottle
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  },
  
  // 图片压缩
  compressImage(filePath, quality = 0.8) {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      
      img.onload = function() {
        const { width, height } = img
        canvas.width = width
        canvas.height = height
        
        ctx.drawImage(img, 0, 0, width, height)
        
        canvas.toBlob((blob) => {
          const reader = new FileReader()
          reader.onload = (e) => resolve(e.target.result)
          reader.readAsDataURL(blob)
        }, 'image/jpeg', quality)
      }
      
      img.onerror = reject
      img.src = filePath
      // #endif
      
      // #ifndef H5
      uni.compressImage({
        src: filePath,
        quality: quality * 100,
        success: (res) => resolve(res.tempFilePath),
        fail: reject
      })
      // #endif
    })
  },
  
  // 内存管理
  memory: {
    // 清理定时器
    clearTimers(timers) {
      timers.forEach(timer => {
        if (timer) {
          clearTimeout(timer)
          clearInterval(timer)
        }
      })
    },
    
    // 清理事件监听器
    removeEventListeners(element, events) {
      if (element && events) {
        events.forEach(({ type, handler }) => {
          element.removeEventListener(type, handler)
        })
      }
    },
    
    // 清理观察器
    disconnectObservers(observers) {
      observers.forEach(observer => {
        if (observer && observer.disconnect) {
          observer.disconnect()
        }
      })
    }
  },
  
  // 数据缓存
  cache: {
    data: new Map(),
    
    // 设置缓存
    set(key, value, ttl = 300000) { // 默认5分钟过期
      const expireTime = Date.now() + ttl
      this.data.set(key, { value, expireTime })
    },
    
    // 获取缓存
    get(key) {
      const item = this.data.get(key)
      if (!item) return null
      
      if (Date.now() > item.expireTime) {
        this.data.delete(key)
        return null
      }
      
      return item.value
    },
    
    // 删除缓存
    delete(key) {
      this.data.delete(key)
    },
    
    // 清空缓存
    clear() {
      this.data.clear()
    }
  },
  
  // 网络请求优化
  request: {
    // 请求队列
    queue: [],
    
    // 并发控制
    concurrent: 3,
    
    // 正在进行的请求数
    running: 0,
    
    // 添加请求到队列
    add(requestFn) {
      return new Promise((resolve, reject) => {
        this.queue.push({
          requestFn,
          resolve,
          reject
        })
        this.process()
      })
    },
    
    // 处理请求队列
    async process() {
      if (this.running >= this.concurrent || this.queue.length === 0) {
        return
      }
      
      this.running++
      const { requestFn, resolve, reject } = this.queue.shift()
      
      try {
        const result = await requestFn()
        resolve(result)
      } catch (error) {
        reject(error)
      } finally {
        this.running--
        this.process()
      }
    }
  },
  
  // 页面性能监控
  monitor: {
    // 页面加载时间
    pageLoadTime: 0,
    
    // 开始计时
    startTiming() {
      this.pageLoadTime = Date.now()
    },
    
    // 结束计时
    endTiming() {
      const loadTime = Date.now() - this.pageLoadTime
      console.log(`页面加载时间: ${loadTime}ms`)
      return loadTime
    },
    
    // 内存使用情况
    getMemoryUsage() {
      // #ifdef H5
      if (performance.memory) {
        return {
          used: performance.memory.usedJSHeapSize,
          total: performance.memory.totalJSHeapSize,
          limit: performance.memory.jsHeapSizeLimit
        }
      }
      // #endif
      return null
    }
  }
}